package com.hankol.winecellar.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.baselibrary.Constants;
import com.baselibrary.activity.BaseFragment;
import com.baselibrary.utils.AppManager;
import com.baselibrary.utils.CommonUtil;
import com.baselibrary.utils.GlideUtils;
import com.baselibrary.utils.NumberUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.signature.ObjectKey;
import com.hankol.winecellar.ImgVideoDetailActivity;
import com.hankol.winecellar.R;
import com.hankol.winecellar.databinding.FragmentBigImagerWineryBinding;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayer;
import com.xinlan.imageeditlibrary.editimage.utils.BaseUtils;
import com.xinlan.imageeditlibrary.editimage.view.imagezoom.ImageViewTouch;
import com.xinlan.imageeditlibrary.editimage.view.imagezoom.ImageViewTouchBase;

/*大图模式*/
public class ImgVideoDetailFragment extends BaseFragment implements ITXLivePlayListener, SeekBar.OnSeekBarChangeListener {


    private FragmentBigImagerWineryBinding mBing;
    private String mUrl;
    private int mType;
    public static final int VIDEO_TYPE = 101;//视频
    public static final int IMG_TYPE = 102;//图片
    private View mBingRoot;

    protected boolean isVisible;
    private boolean isPrepared;
    private boolean isFirst = true;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            lazyLoad();
        } else {
            isVisible = false;
            if (VIDEO_TYPE == mType) {
                videoPause();
            }
        }
    }

    public static ImgVideoDetailFragment newInstance(String param1, String param2) {
        ImgVideoDetailFragment fragment = new ImgVideoDetailFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_big_imager_winery;
    }

    @Override
    protected void init() {
        if (getArguments() != null) {
            mUrl = getArguments().getString("url");
            mType = getArguments().getInt(Constants.WIKI_IMGPAGER_TYPE);
        }
        mBing = (FragmentBigImagerWineryBinding) getDataBinding();
        isPrepared = true;
        lazyLoad();
    }

    private static final String TAG = "ViewImagerFragment";

    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirst) {
            return;
        }

        try {
            initData();
        } catch (Exception e) {
            e.getMessage();
        }
        isFirst = false;
    }

    private void initData() {
        if (VIDEO_TYPE == mType) {
            mBing.previewProgressBar.setVisibility(View.GONE);
            mBing.ivImager.setVisibility(View.GONE);
            mBing.rlVideo.setVisibility(View.VISIBLE);
            mBing.llVideoProgress.setVisibility(View.GONE);
            initPlayerView(mUrl);

            mBing.ivMaterialVoice.setOnClickListener(view -> {
                if (mVodPlayer != null) {
                    if (mBing.ivMaterialVoice.isSelected()) {
                        //关闭声音
                        mVodPlayer.setMute(true);//静音设置
                        mBing.ivMaterialVoice.setImageResource(R.drawable.ic_material_voice_false);
                    } else {
                        //打开声音
                        mVodPlayer.setMute(false);//有音设置
                        mBing.ivMaterialVoice.setImageResource(R.drawable.ic_material_voice_true);
                    }
                    mBing.ivMaterialVoice.setSelected(!mBing.ivMaterialVoice.isSelected());
                }
            });
        } else {
            mBing.previewProgressBar.setVisibility(View.VISIBLE);
            mBing.rlVideo.setVisibility(View.GONE);
            mBing.llVideoProgress.setVisibility(View.GONE);
            mBing.ivImager.setVisibility(View.VISIBLE);

            RequestOptions userAvatarOptions = new RequestOptions()
                    .signature(new ObjectKey(System.currentTimeMillis()));
            Glide.with(getActivity())
                    .applyDefaultRequestOptions(userAvatarOptions)
                    .asBitmap().load(mUrl)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                            mBing.previewProgressBar.setVisibility(View.GONE);
                            int mBitHeight = bitmap.getHeight();
                            int mScreenHeight = BaseUtils.getScreenHeight(getActivity());
                            //复制一份bitmap，避免加载bitmap后，bitmap被回收
                            Bitmap bitmap2 = null;
                            try {
                                bitmap2 = Bitmap.createBitmap(bitmap);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (mBitHeight >= mScreenHeight * 5) {
                                GlideUtils.loadImg_101BlackPlaceHolder(getContext(), mUrl, mBing.ivImager);
//                                Glide.with(getActivity()).load(bitmap2).into(mBing.ivImager);
                                mBing.ivImager.setLongGraph(true);
                            } else {
                                GlideUtils.loadImg_101BlackPlaceHolder(getContext(), mUrl, mBing.ivImager);
//                                Glide.with(getActivity()).load(bitmap2).into(mBing.ivImager);
                                mBing.ivImager.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
                            }
                        }
                    });

            mBing.ivImager.setSingleTapListener(new ImageViewTouch.OnImageViewTouchSingleTapListener() {
                @Override
                public void onSingleTapConfirmed() {
                    AppManager.getAppManager().finishActivity(ImgVideoDetailActivity.class);
                }
            });
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isPrepared) {
            return;
        }
        videoResume();

    }

    public void videoResume() {
        if (mVodPlayer != null) {
            mVodPlayer.resume();
            mBing.videoPlay.setSelected(true);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        videoPause();
    }

    public void videoPause() {
        if (mVodPlayer != null) {
            mVodPlayer.pause();

            mBing.videoPlay.setSelected(false);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        videoPause();
    }

    @Override
    public void onDestroy() {
        stopUpdateTimer();
        super.onDestroy();

    }

    /**
     * SDK player 相关
     */
    private TXVodPlayer mVodPlayer = null;

    private void initPlayerView(final String url) {

        mBing.videoView.setLogMargin(12, 12, 110, 60);
        mBing.videoView.showLog(false);
        mBing.videoView.setKeepScreenOn(true);
        if (mVodPlayer == null) {
            mVodPlayer = new TXVodPlayer(getContext());
        }

        mVodPlayer.setVodListener(new ITXVodPlayListener() {
            @Override
            public void onPlayEvent(TXVodPlayer txVodPlayer, int event, Bundle bundle) {

            }

            @Override
            public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {

            }
        });
        mVodPlayer.setPlayListener(new ITXLivePlayListener() {
            @Override
            public void onPlayEvent(int i, Bundle bundle) {
            }

            @Override
            public void onNetStatus(Bundle bundle) {

            }
        });
        mVodPlayer.setPlayerView(mBing.videoView);
        mVodPlayer.setAutoPlay(true);
        mVodPlayer.setPlayListener(this);
        mVodPlayer.enableHardwareDecode(false); // 是否使用硬解码
        mVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);// player 渲染角度
        mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);//player 渲染模式
        int result = mVodPlayer.startVodPlay(url); // result返回值：0 success;  -1 empty url; -2 invalid url; -3 invalid playType;
        Log.d(TAG, "initPlayerView: result == " + result);
        if (result == 0) {
            mBing.videoPlay.setSelected(true);
            mBing.rlMaterialPlayIng.setVisibility(View.VISIBLE);
            showVideoProgressInfo();
            hidePlayerView();
        }

        mBing.rlVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBing.videoPlay.setVisibility(mBing.videoPlay.isShown() ? View.GONE : View.VISIBLE);
                mBing.rlMaterialPlayIng.setVisibility(mBing.videoPlay.isShown() ? View.VISIBLE : View.GONE);
                if (mBing.videoPlay.isShown()) {
                    hidePlayerView();
                }
            }
        });
        mBing.videoPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hidePlayerView();
                if (mVodPlayer != null) {
                    if (mVodPlayer.isPlaying()) {
                        mVodPlayer.pause();
                        mBing.videoPlay.setSelected(false);
                    } else {
                        mVodPlayer.resume();
                        mBing.videoPlay.setSelected(true);
                    }
                }
            }
        });
        mBing.sbMaterialSpeed.setOnSeekBarChangeListener(this);
        mBing.llMaterialSpeed.setOnTouchListener((v, event) -> {
            Rect seekRect = new Rect();
            mBing.sbMaterialSpeed.getHitRect(seekRect);

            if ((event.getY() >= (seekRect.top - 50)) && (event.getY() <= (seekRect.bottom + 50))) {

                float y = seekRect.top + seekRect.height() / 2;
                float x = event.getX() - seekRect.left;
                if (x < 0) {
                    x = 0;
                } else if (x > seekRect.width()) {
                    x = seekRect.width();
                }
                MotionEvent me = MotionEvent.obtain(event.getDownTime(), event.getEventTime(),
                        event.getAction(), x, y, event.getMetaState());
                return mBing.sbMaterialSpeed.onTouchEvent(me);

            }
            return false;

        });
    }

    private void hidePlayerView() {
        if (progressUpdateTimer != null) {
            progressUpdateTimer.removeMessages(UpdatePlayer);
            progressUpdateTimer.sendEmptyMessageDelayed(UpdatePlayer, 3000);
        }
    }

    private void showVideoProgressInfo() {
        if (mVodPlayer != null) {
            startUpdateTimer();
            int curPosition = (int) mVodPlayer.getCurrentPlaybackTime();
            int duration = (int) mVodPlayer.getPlayableDuration();
            int bufferPosition = (int) mVodPlayer.getBufferDuration();
            mBing.currentDuration.setText(CommonUtil.Formatter.formatTime((int) (curPosition * 1000)));
            mBing.totalDuration.setText(CommonUtil.Formatter.formatTime((int) (duration * 1000)));
//            mBing.tvProgressCurrent.setText(CommonUtil.Formatter.formatTime((int) (curPosition * 1000)));
//            mBing.tvProgressTotal.setText("/" + CommonUtil.Formatter.formatTime((int) (duration * 1000)));
            mBing.progress.setMax((int) duration);
            mBing.progress.setSecondaryProgress((int) bufferPosition);
            mBing.progress.setProgress((int) curPosition);
//            mBing.sbMaterialSpeed.setMax((int) duration);
//            mBing.sbMaterialSpeed.setSecondaryProgress((int) bufferPosition);
//            mBing.sbMaterialSpeed.setProgress((int) curPosition);
            if (((int) (curPosition * 1000) != 0) && (int) (curPosition * 1000) == (int) (duration * 1000)) {//播放结束
//                mBing.videoPlay.setSelected(false);
//                mBing.videoPlay.setVisibility(View.VISIBLE);
            }
        }
    }

    private void startUpdateTimer() {
        if (progressUpdateTimer != null) {
            progressUpdateTimer.removeMessages(UpdateTimer);
            progressUpdateTimer.sendEmptyMessageDelayed(UpdateTimer, 1000);
        }
    }

    private void stopUpdateTimer() {
        if (progressUpdateTimer != null) {
            progressUpdateTimer.removeMessages(UpdateTimer);
            progressUpdateTimer.removeMessages(UpdatePlayer);
        }
    }

    private final int UpdateTimer = 100;
    private final int UpdatePlayer = 200;
    @SuppressLint("HandlerLeak")
    private Handler progressUpdateTimer = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UpdateTimer:
                    showVideoProgressInfo();
                    break;
                case UpdatePlayer:
                    mBing.videoPlay.setVisibility(View.GONE);
                    mBing.rlMaterialPlayIng.setVisibility(View.GONE);
                    break;
            }
        }
    };


    @Override
    public void onPlayEvent(int event, Bundle bundle) {
        switch (event) {
            case TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED:
                mBing.pbBigImager.setVisibility(View.GONE);
                break;
            case TXLiveConstants.PLAY_EVT_PLAY_PROGRESS:
                int progress = bundle.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                int duration = bundle.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);
                mBing.sbMaterialSpeed.setProgress(progress);
                mBing.sbMaterialSpeed.setMax(duration);
                mBing.tvProgressTotal.setText("/" + NumberUtils.stringForTime(duration));
                mBing.tvProgressCurrent.setText(NumberUtils.stringForTime(progress));
                break;
        }
    }

    @Override
    public void onNetStatus(Bundle bundle) {

    }

    private int mSlidePro;

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        mSlidePro = seekBar.getProgress();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //手指抬起获取当前SeekBar进度
        if (mVodPlayer != null) {
            mVodPlayer.seek(mSlidePro / 1000);
            setVideoPlaySate(true);
        }
    }


    /**
     * 视频播放/暂停  设置元素状态
     *
     * @param b true = 播放
     */
    public void setVideoPlaySate(boolean b) {
        if (mVodPlayer != null) {
            if (b) {
                mBing.videoPlay.setVisibility(View.VISIBLE);
                mBing.rlMaterialPlayIng.setVisibility(View.VISIBLE);
                mVodPlayer.resume();
                mBing.videoPlay.setSelected(true);
                startUpdateTimer();
            } else {
                mBing.videoPlay.setVisibility(View.VISIBLE);
                mBing.rlMaterialPlayIng.setVisibility(View.GONE);
                stopUpdateTimer();
                mVodPlayer.pause();
                mBing.videoPlay.setVisibility(View.VISIBLE);
                mBing.videoPlay.setSelected(false);
            }
        }
    }

}
